package org.justdroid.justdroid;

import java.util.HashMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver{
	private HashMap<String, String> senderDetails;
	
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String sender;
            if (bundle != null){
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++) {
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        sender = msgs[i].getOriginatingAddress();
                        senderDetails = new ContactManager(context).getNameFromNumber(sender);
                        //play ringtone
                        Utils.ringtone = RingtoneManager.getRingtone(context, Settings.System.DEFAULT_NOTIFICATION_URI);
                        Utils.ringtone.play();
                        if(senderDetails.get("name") != null) {
                        	if(Utils.isAccessibilityEnabled(context))
                        		TTS.speak("Received text message from " + senderDetails.get("name") + " " + senderDetails.get("type"));
                        }
                        else {
                        	if(Utils.isAccessibilityEnabled(context))
                        		TTS.speak("Received text message from " + sender);
                        }
                    }
                }catch(Exception e){
                	e.printStackTrace();
                }
                Intent intentObject  = new Intent(context, TextMessagesApp.class);
                intentObject.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intentObject);
            }
        }
    }
}